package cc.shacocloud.mirage.kotlin.restful

import cc.shacocloud.mirage.kotlin.mirageLaunch
import cc.shacocloud.mirage.restful.HandlerInterceptor
import cc.shacocloud.mirage.restful.HttpRequest
import cc.shacocloud.mirage.restful.HttpResponse
import cc.shacocloud.mirage.restful.VertxInvokeHandler
import io.vertx.core.Future

/**
 * 基于 kotlin 协程的处理器拦截器
 * @author 思追(shaco)
 *
 */
interface CoroutineHandlerInterceptor : HandlerInterceptor {

    /**
     * 转为协程处理方法
     */
    override fun preHandle(request: HttpRequest, response: HttpResponse, handler: VertxInvokeHandler): Future<Boolean> {
        return mirageLaunch { doPreHandle(request, response, handler) }
    }

    /**
     * 转为协程处理方法
     */
    override fun afterCompletion(
        request: HttpRequest, response: HttpResponse, handler: VertxInvokeHandler, cause: Throwable?
    ): Future<Void?> {
        return mirageLaunch {
            doAfterCompletion(request, response, handler, cause)
            return@mirageLaunch null
        }
    }

    /**
     * @see #preHandle
     */
    suspend fun doPreHandle(request: HttpRequest, response: HttpResponse, handler: VertxInvokeHandler): Boolean {
        return true
    }

    /**
     * @see #afterCompletion
     */
    suspend fun doAfterCompletion(
        request: HttpRequest, response: HttpResponse, handler: VertxInvokeHandler, cause: Throwable?
    ) {
    }

}